<script setup>
import { shallowRef, watch, ref } from 'vue'
import CompA from "@/components/6BuildInComp/3KeepAliveCache/ComA.vue"
import CompB from "@/components/6BuildInComp/3KeepAliveCache/ComB.vue"
import CompC from "@/components/6BuildInComp/3KeepAliveCache/ComC.vue"

const current = shallowRef(CompA)

const include = ref([])

watch(current, (newVal, oldVal) => {
  if (oldVal) {
    //include.value = include.value.filter(name => name !== oldVal.name)
  }
  if (newVal) {
    if (!include.value.includes(newVal.name)) {
      //include.value.push(newVal.name)
    }
  }
})



function createComponent(componentName) {
  if (componentName === "ComA") {
    current.value = CompA
  } else if (componentName === "ComB") {
    current.value = CompB
  } else if (componentName === "ComC") {
    current.value = CompC
  }
  if (!include.value.includes(componentName)) {
    include.value.push(componentName)
  }
}

function switchComponent(componentName) {
  if (componentName === "ComA") {
    current.value = CompA
  } else if (componentName === "ComB") {
    current.value = CompB
  } else if (componentName === "ComC") {
    current.value = CompC
  }
}

function destroyComponent(name) {
  include.value = include.value.filter(item => item !== name)
  let lastComponent = include.value[include.value.length - 1]
  switchComponent(lastComponent)
}
</script>

<template>
  <div class="demo">
    <h2>菜单</h2>
    <button @click="createComponent('ComA')">新建组件A</button>
    <button @click="createComponent('ComB')">新建组件B</button>
    <button @click="createComponent('ComC')">新建组件C</button>
    <hr/>

    <button v-for="componentName in include" :key="componentName" @click="switchComponent(componentName)" @dblclick="destroyComponent(componentName)">
       {{ componentName }}
    </button>

    <KeepAlive :include="include">
      <component :is="current"></component>
    </KeepAlive>
    <pre>{{ include }}</pre>

  </div>
</template>